/*
 * @Author: silas 
 * @Date: 2021-05-24 10:01:08 
 * @Last Modified by: silas
 * @Last Modified time: 2021-05-26 09:43:33
 */
<template>
    <div class="onw_container">
        <header>
            <p>政企团购优惠到期预警</p>
        </header>
        <el-form :inline="true" :model="form" class="main_searchBar">
            <el-form-item label="区域:">
                <dx-cascader :area_id.sync="form.areaId" ref="cascader" />
            </el-form-item>
            <!-- <el-form-item label="账期:">
                <el-date-picker
                    size="mini"
                    v-model="form.month"
                    value-format="yyyyMM"
                    type="month"
                    placeholder="选择年月"
                    :picker-options="pickerOptions"
                ></el-date-picker>
            </el-form-item> -->
            <el-form-item label="团购优惠">
                <el-cascader size="mini" ref="cascader1" :props="prop" expandTrigger="hover" :show-all-levels="false" clearable @change="changeHandle($event)" v-model="form.offerNbr" />
                <!-- <el-select v-model="form.offerNbr" size="mini">
                    <el-option v-for="(it, i) in offerNbr" :key="i" :label="it.areaName" :value="it.areaId"></el-option>
                </el-select> -->
            </el-form-item>
            <el-form-item label="优惠失效时间">
                <el-select v-model="form.dateType" size="mini">
                    <el-option v-for="(it, i) in dateType" :key="i" :label="it" :value="it"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    size="mini"
                    @click="search()"
                    type="primary"
                    id="search_btn"
                    >查询</el-button
                >
                <el-button
                    size="mini"
                    type="success"
                    id="export_btn"
                    @click="handle_export"
                    >导出</el-button
                >
            </el-form-item>
        </el-form>

        <ux-grid
            size="mini"
            id="tablePx"
            ref="tablePx"
            :header-row-style="{ background: '#eef1f6' }"
            border
            :stripe="true"
            :widthResize="true"
            :height="height"
            style="width: 100%"
            v-loading="showTableLoading"
            show-overflow="tooltip"
            show-header-overflow="title"
        >
            <!-- <ux-table-column
                type="index"
                width="60"
                title="序号"
                fixed="left"
                align="center"
            /> -->
            <ux-table-column
                :title="item.label"
                min-width="150"
                v-for="(item, i) in columns"
                :key="'item' + i"
                align="center"
                :field="item.value"
            />
        </ux-grid>
    </div>
</template>

<script>
import { $budgetAPI, $budget } from "@/api";
import qs from "qs";
import { getCookie, setCookie } from "@/common/js/cookie";
import prefixAPI from "@/api/prefixAPI"; // prefixAPI 前缀
const url = prefixAPI.pack;
import {
    setSessionStorage,
    getSessionStorage,
    removeSessionStorage,
} from "@/common/js/storage";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
    data() {
        let that = this;
        let accountInfo = JSON.parse(getSessionStorage('accountInfo'));
        return {
            form: {
                areaId: "",
                offerNbr: '0',
                dateType: '当月',
            },
            showTableLoading: false,
            height: window.innerHeight - 60 - 30 - 175,
            tableData: [],
            columns: [],
            offerNbr: [],
            dateType: ['当月','下月','下下月'],
            prop: {
                lazy: true,
                checkStrictly: true,
                lazyLoad(node, resolve) {
                    const { level } = node;
                    var areaId;
                    var lvl;
                    var areaName;
                    if (level == 0) {
                        // areaId =  accountInfo.areaId;
                        // areaName = that.position ? accountInfo.parentName : accountInfo.areaName;
                        // lvl = accountInfo.areaLvl;
                        resolve([{ value: '0', label: '全部', lvl: 1 }]);
                    } else {
                        areaId = node.value;
                        lvl = node.data.lvl;
                        $budgetAPI.getGroupType(
                            {
                                areaId,
                                lvl: 0
                            },
                            res => {
                                if (res.code == 0) {
                                    let nodes = res.content.map((item, index) => {
                                        return {
                                            value: item.areaId,
                                            label: item.areaName,
                                            lvl: item.areaLvl !== lvl ? item.areaLvl : ''
                                        };
                                    });
                                    resolve(nodes);
                                } else {
                                    that.alertError(res);
                                }
                            }
                        );
                    }
                }
            }
        };
    },
    methods: {
        getHeight() {
            this.height = window.innerHeight - 60 - 30 - 175;
        },
        // 初始化列表接口
        getInitList() {
            var that = this,  offerNbr;
            this.showTableLoading = true;

            offerNbr = typeof that.form.offerNbr == 'string' ? '0' : that.form.offerNbr.slice(-1).toString();
            $budgetAPI.getListForGroupBuying(
                {
                    areaId: that.form.areaId,
                    dateType: that.form.dateType,
                    offerNbr: offerNbr
                },
                (res) => {
                    if (res.code == 0) {
                        this.tableData = res.content.data;
                        that.columns =  Array.from(new Array(res.content.keys.length), (it) => it = {label: '', value: ''});

                        res.content.keys.map((it, i)=> {
                            that.columns[i]['value'] = it
                        })
                         res.content.names.map((it, i)=> {
                            that.columns[i]['label'] = it
                        })
                        this.$refs.tablePx.reloadData(this.tableData);
                    } else {
                        this.tableData = [];
                        this.$refs.tablePx.reloadData([]);
                    }
                    this.showTableLoading = false;
                },
                (err) => {
                    console.log(err);
                }
            );
        },
        search() {
            this.getInitList();
        },
        handle_export() {
            const offerNbr = typeof this.form.offerNbr == 'string' ? '0' : this.form.offerNbr.slice(-1).toString();
            var params = {
                areaId: this.form.areaId,
                offerNbr: offerNbr,
                dateType: this.form.dateType,
                token: getCookie("token"),
            };
            window.open(
                `${url}/governmentCust/exportDiscountReachData?${qs.stringify(params)}`,
                "_self"
            );
        },
        async initDate() {
            this.form.month = await this.getMonth();
            // this.offerNbr = await this.getTypes();
            this.getInitList();
        },
        getMonth() {
            return new Promise((resolve) => {
                $budgetAPI.incomeKeepRegionalMonth({ maximum: 17 }, (res) => {
                    resolve(res.content);
                });
            });
        },
        changeHandle(event) {
            if (event) {
                let arr = event.slice(0);
                let value = arr.pop();
                this.$emit('update:form.offerNbr', value);
                // 触发父组件的change函数
                this.$emit('change', value);
                let data = this.$refs.cascader1.getCheckedNodes()[0] ? this.$refs.cascader1.getCheckedNodes()[0].data : '';
                if (data) {
                    // this.$emit('update:area_name', data.label);
                    // this.$emit('update:area_lvl', data.lvl);
                }
                // this.form.offerNbr = value
                // console.log(this.form.offerNbr, data);
                this.$refs.cascader1.dropDownVisible = false;
            }
        },
        clear() {
            let obj = {};
            obj.stopPropagation = () => {};
            try {
                this.$refs.cascader1.clearValue(obj);
            } catch (err) {
                this.$refs.cascader1.handleClear(obj);
            }
        },
    },
    created() {
        this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
        this.form.areaId = this.accountInfo.areaId;
        this.initDate();
        window.addEventListener("resize", this.getHeight);
    },
    destroyed() {
        // 计算高度
        window.removeEventListener("resize", this.getHeight);
    },
};
</script>

<style lang="scss" scoped>
.onw_container {
    width: 100%;
    height: 100%;
    & > header {
        font-size: 16px;
        margin-bottom: 10px;
    }
    .page_box {
        display: flex;
        justify-content: flex-end;
    }
}
</style>
